﻿using SimpleX;
using System.IO;

namespace SimpleX
{
    public static partial class ServicesExtension
    {
        public static void AddJsonFile(this ConfigurationManager configurationManager)
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            //if (string.IsNullOrWhiteSpace(environment))
            //    throw new Exception($"为了加载不同环境对应的Json文件,您必须要配置环境变量 ASPNETCORE_ENVIRONMENT 对应的值,否则项目无法启动");

            //没有设置环境变量就默认生产环境
            if (string.IsNullOrWhiteSpace(environment))
                environment = "Production";

            var jsonDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "JsonConfig");
            if (!Directory.Exists(jsonDir))
                Directory.CreateDirectory(jsonDir);
            Console.WriteLine($"加载Json配置文件,配置文件目录: {jsonDir}, 环境: {environment}");

            var jsonFiles = Directory.GetFiles(jsonDir, $"*.{environment}.json").ToList();
            jsonFiles.AddRange(Directory.GetFiles(jsonDir, $"*.All.json"));

            for (int i = 0; i < jsonFiles.Count; i++)
            {
                var jsonFile = jsonFiles[i];
                var builder = configurationManager.AddJsonFile(jsonFile, false, true);

                if (i == jsonFiles.Count - 1)
                    builder.Build();

                App.ConfigJsonFiles.Add(jsonFile);
            }
        }
    }
}